<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Auth extends CI_Controller
{
	function __construct()
	{
		parent::__construct();

		$this->load->helper(array('form', 'url'));
		$this->load->library('form_validation');
		$this->load->library('security');
		$this->load->library('tank_auth');
		$this->lang->load('tank_auth');


		//added by cyq/stone59 at 20210921
		$this->ci =& get_instance();
		$this->load->library('session');
		$this->ci->load->model('tank_auth/users');

	}
	//用于生成html页面的通用部分
	private function get_share_pagedata()
	{
		$pagedata['htmlhead'] = $this->load->view('htmlpage/htmlhead', '', true);
		$pagedata['logobar'] = $this->load->view('htmlpage/logobar', '', true);
		$pagedata['navbar'] = $this->load->view('htmlpage/navbar', '', true);
		$pagedata['footbar'] = $this->load->view('htmlpage/footbar', '', true);
		return $pagedata;
	}

	//将数组转换成json，并输出
	private function array_to_json($array)
	{
		$json_string = json_encode($array);
		echo $json_string;
	}

	public function checklogin()
	{

		// if ($login_userid == $_POST['uid']) {

		$this->load->library('tank_auth');
		$this->lang->load('tank_auth');
		if ($this->tank_auth->is_logged_in()) {
			// if ($this->tank_auth->get_user_id() == $_POST['uid']) {
			$login_userid = $this->tank_auth->get_user_id();
			$result_arr = array(
				'status' => 1,
				'message' => '保持联系！',
				'uid' => $login_userid
			);
		} else {
			$result_arr = array(
				'status' => 0,
				'message' => '你未登录或已经过期了，请登录！',
				'uid' => null
			);
		}
		$json_string = json_encode($result_arr);
		echo $json_string;
	}

	//检查是否已登录
	public function if_login()
	{
		$this->load->library('tank_auth');
		$this->lang->load('tank_auth');
		if ($this->tank_auth->is_logged_in()) {
			$result_arr = array(
				'status' => 1,
				'message' => '已登录' ,
				'data' => array(
					'login_uid' => $this->tank_auth->get_user_id(),
					'login_username' => $this->tank_auth->get_username(),
				)
			);
		} else {
			$result_arr = array(
				'status' => 1,
				'message' => '尚未登录' ,
				'data' => array(
					'login_uid' => 0,
					'login_username' => ""
				)
			);
		}
		$this->array_to_json($result_arr);
	}

	/**
	 * Login user by wx，微信扫码后将跳转到本网址，进行后续检查
	 * ADDED by cyq 20210920
	 * @return void
	 */	
	public function wx_login(){
		// echo $_GET['code'];
		$APPID = 'wxffe98e95f9cbacfe';
		$SECRET = '54c34bf2a6de490dc7d3ab767241b9af';
		$wx_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$APPID."&secret=".$SECRET."&code=".$_GET['code']."&grant_type=authorization_code";		
		$result_json = file_get_contents($wx_url);

		// true表示解析成数组
		$result = json_decode($result_json,true);
		// print_r($result);

		// 如果数组存在errcode键，出错了
		if(array_key_exists('errcode', $result)){
			// print_r($result);
			$pagedata['redirect_url']="/";
			$pagedata['message'] = "出现错误：<br>".var_export($result);
			$this->load->view('htmlpage/message.php',$pagedata);
			return;
		}else{
			// var_dump($result);
			$this->session->set_userdata($result);
			// print_r($this->session->all_userdata());
			// print_r($_SESSION);
		}

		//通过wx_openid进行尝试登录
		if ($this->tank_auth->wx_login($result['openid'], 1)) {								// success
			
			// redirect('');
			$pagedata['redirect_url']="/";
			$pagedata['message'] = "微信登录成功！将跳转回首页";
			$this->load->view('htmlpage/message.php',$pagedata);
			
		} else {
			// $errors = $this->tank_auth->get_error_message();
			// if (isset($errors['banned'])) {								// banned user
			// 	$this->_show_message($this->lang->line('auth_message_banned') . ' ' . $errors['banned']);
			// } elseif (isset($errors['not_activated'])) {				// not activated user
			// 	redirect('/auth/send_again/');
			// } else {													// fail
			// 	foreach ($errors as $k => $v)	$data['errors'][$k] = $this->lang->line($v);
			// }

			// 如果没有，则提示用户进行绑定注册
				// echo "你没有注册或将微信绑定到用户！";

			$pagedata['redirect_url']="";
			$pagedata['message'] = "你没有注册或将微信绑定到用户！<br>请你在本站注册登录，并绑定微信后，可用微信登录。";
			$this->load->view('htmlpage/message.php',$pagedata);	


		}
	}
	
	/**
	 * Login user by wx
	 * ADDED by cyq 20210920
	 * 微信绑定
	 * @return void
	 */	
	public function wx_bind(){
		// echo $_GET['code'];
		$APPID = 'wxffe98e95f9cbacfe';
		$SECRET = '54c34bf2a6de490dc7d3ab767241b9af';
		$wx_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$APPID."&secret=".$SECRET."&code=".$_GET['code']."&grant_type=authorization_code";		
		$result_json = file_get_contents($wx_url);
		// true表示解析成数组
		$result = json_decode($result_json,true);
		// print_r($result);
		// 如果数组存在errcode键
		if(array_key_exists('errcode', $result)){
			$pagedata['redirect_url']="/";
			$pagedata['message'] = "出现错误：<br>".var_export($result);
			$this->load->view('htmlpage/message.php',$pagedata);
			return;
		}else{
			// var_dump($result);
			$this->session->set_userdata($result);
			// print_r($this->session->all_userdata());
			// print_r($_SESSION);
			// 如果session中同时存在微信id和user_id，则可以绑定
			if($this->session->userdata('openid')&&$this->session->userdata('user_id')){
				if($this->ci->users->set_wx_openid(
					$this->session->userdata('user_id'),
					$this->session->userdata('openid')
				)){//success
					
					// $this->_show_message($this->lang->line('微信绑定成功！'));
					$pagedata['redirect_url']="/";
					$pagedata['message'] = "微信绑定成功，将跳转回首页！";
					$this->load->view('htmlpage/message.php',$pagedata);	
				}else{
					
					// $this->_show_message($this->lang->line('绑定失败'));
					$pagedata['redirect_url']="";
					$pagedata['message'] = "微信绑定失败";
					$this->load->view('htmlpage/message.php',$pagedata);	
				}
	
				// if ($this->tank_auth->change_password(
				// 	$this->form_validation->set_value('old_password'),
				// 	$this->form_validation->set_value('new_password')
				// )) {	// success
				// 	$this->_show_message($this->lang->line('auth_message_password_changed'));
				// } else {														// fail
				// 	$errors = $this->tank_auth->get_error_message();
				// 	foreach ($errors as $k => $v)	$data['errors'][$k] = $this->lang->line($v);
				// }
			}

		}


	}

	/**
	 * Login user by API
	 * ADDED by cyq 20210719
	 * @return void
	 */
	public function login_api()
	{
		//如果已登录，直接返回
		if ($this->tank_auth->is_logged_in()) {
			$result_arr = array(
				'status' => 0,
				'code' => 0,
				'message' => '你已登录',
				'data' => array(
					'login_uid' => $this->tank_auth->get_user_id(),
					'login_username' => $this->tank_auth->get_username(),
				)
			);									// logged in
			$this->array_to_json($result_arr);
			return;
		} else {
			$data['errors'] = array();
			$data['login_by_username'] = ($this->config->item('login_by_username', 'tank_auth') and
				$this->config->item('use_username', 'tank_auth'));
			$data['login_by_email'] = $this->config->item('login_by_email', 'tank_auth');
			// print_r($_REQUEST);
			if ($this->tank_auth->login(
				//客户端有效性验证
				// $this->form_validation->set_value('login'),
				// $this->form_validation->set_value('password'),
				// $this->form_validation->set_value('remember'),

				$_REQUEST['login'],
				$_REQUEST['password'],
				$_REQUEST['remember'],
				$data['login_by_username'],
				$data['login_by_email']
			)) {								// success
				$result_arr = array(
					'status' => 0,
					'message' => '你已登录成功',
					'data' => array(
						'login_uid' => $this->tank_auth->get_user_id(),
						'login_username' => $this->tank_auth->get_username(),
					)
				);									// logged in
				$this->array_to_json($result_arr);
			} else {
				$errors = $this->tank_auth->get_error_message();
				// print_r($errors);
				if (isset($errors['banned'])) {								// banned user
					$this->_show_message($this->lang->line('auth_message_banned') . ' ' . $errors['banned']);
				} elseif (isset($errors['not_activated'])) {				// not activated user
					redirect('/auth/send_again/');
				} else {													// fail
					foreach ($errors as $k => $v)	$data['errors'][$k] = $this->lang->line($v);
				}
				$result_arr = array(
					'status' => 0,
					'message' => '登录不成功',
					'data' => $errors,
				);									// logged in
				$this->array_to_json($result_arr);
			}
		}
	}


/**
	 * 微信小程序登录
	 * ADDED by cyq 20220131
	 * @return void
	 */	
	public function miniprogram_login(){
		echo $_GET['code'];
		// $APPID = 'wxffe98e95f9cbacfe';
		$SECRET = '54c34bf2a6de490dc7d3ab767241b9af';

		$APPID = 'wxfc60a30d07149f70';//环保知识卡小程序
		$SECRET = '54c34bf2a6de490dc7d3ab767241b9af';
		
		$APPID = 'wx940c2d88c90a92b3';//chenyuquan小程序测试号
		$SECRET = 'db76a0e58b4c0dc9a309553f902b40af';
		// https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

		$wx_url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$APPID."&secret=".$SECRET."&js_code=".$_GET['code']."&grant_type=authorization_code";		
		$result_json = file_get_contents($wx_url);

		// true表示解析成数组
		$result = json_decode($result_json,true);
		print_r($result);

		// 如果数组存在errcode键，出错了
		if(array_key_exists('errcode', $result)){
			// print_r($result);
			$pagedata['redirect_url']="/";
			$pagedata['message'] = "出现错误：<br>".var_export($result);
			$this->load->view('htmlpage/message.php',$pagedata);
			return;
		}else{
			// var_dump($result);
			$this->session->set_userdata($result);
			// print_r($this->session->all_userdata());
			// print_r($_SESSION);
		}

		//通过wx_openid进行尝试登录
		if ($this->tank_auth->wx_app_login($result['openid'], 1)) {								// success
			
			// redirect('');
			$pagedata['redirect_url']="/";
			$pagedata['message'] = "微信登录成功！将跳转回首页";
			$this->load->view('htmlpage/message.php',$pagedata);
			
		} else {
			// $errors = $this->tank_auth->get_error_message();
			// if (isset($errors['banned'])) {								// banned user
			// 	$this->_show_message($this->lang->line('auth_message_banned') . ' ' . $errors['banned']);
			// } elseif (isset($errors['not_activated'])) {				// not activated user
			// 	redirect('/auth/send_again/');
			// } else {													// fail
			// 	foreach ($errors as $k => $v)	$data['errors'][$k] = $this->lang->line($v);
			// }

			// 如果没有，则提示用户进行绑定注册
				// echo "你没有注册或将微信绑定到用户！";

			$pagedata['redirect_url']="";
			$pagedata['message'] = "你没有注册或将微信绑定到用户！<br>请你在本站注册登录，并绑定微信后，可用微信登录。";
			$this->load->view('htmlpage/message.php',$pagedata);	


		}
	}


	function index()
	{
		if ($message = $this->session->flashdata('message')) {
			//			$this->load->view('auth/general_message', array('message' => $message));
			$pagedata = $this->get_share_pagedata();
			$pagedata['main_content'] = $this->load->view('auth/general_message', array('message' => $message), true);
			$this->load->view('htmlpage/page_for_auth', $pagedata);
		} else {
			redirect('/auth/login/');
		}
	}

	/**
	 * Login user on the site
	 *
	 * @return void
	 */
	function login()
	{
		if ($this->tank_auth->is_logged_in()) {									// logged in
			redirect('');
		} elseif ($this->tank_auth->is_logged_in(FALSE)) {						// logged in, not activated
			redirect('/auth/send_again/');
		} else {
			$data['login_by_username'] = ($this->config->item('login_by_username', 'tank_auth') and
				$this->config->item('use_username', 'tank_auth'));
			$data['login_by_email'] = $this->config->item('login_by_email', 'tank_auth');

			$this->form_validation->set_rules('login', 'Login', 'trim|required|xss_clean');
			$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
			$this->form_validation->set_rules('remember', 'Remember me', 'integer');

			// Get login for counting attempts to login
			if (
				$this->config->item('login_count_attempts', 'tank_auth') and
				($login = $this->input->post('login'))
			) {
				$login = $this->security->xss_clean($login);
			} else {
				$login = '';
			}

			$data['use_recaptcha'] = $this->config->item('use_recaptcha', 'tank_auth');
			if ($this->tank_auth->is_max_login_attempts_exceeded($login)) {
				if ($data['use_recaptcha'])
					$this->form_validation->set_rules('recaptcha_response_field', 'Confirmation Code', 'trim|xss_clean|required|callback__check_recaptcha');
				else
					$this->form_validation->set_rules('captcha', 'Confirmation Code', 'trim|xss_clean|required|callback__check_captcha');
			}
			$data['errors'] = array();

			if ($this->form_validation->run()) {								// validation ok
				if ($this->tank_auth->login(
					$this->form_validation->set_value('login'),
					$this->form_validation->set_value('password'),
					$this->form_validation->set_value('remember'),
					$data['login_by_username'],
					$data['login_by_email']
				)) {								// success
					redirect('');
				} else {
					$errors = $this->tank_auth->get_error_message();
					if (isset($errors['banned'])) {								// banned user
						$this->_show_message($this->lang->line('auth_message_banned') . ' ' . $errors['banned']);
					} elseif (isset($errors['not_activated'])) {				// not activated user
						redirect('/auth/send_again/');
					} else {													// fail
						foreach ($errors as $k => $v)	$data['errors'][$k] = $this->lang->line($v);
					}
				}
			}
			$data['show_captcha'] = FALSE;
			if ($this->tank_auth->is_max_login_attempts_exceeded($login)) {
				$data['show_captcha'] = TRUE;
				if ($data['use_recaptcha']) {
					$data['recaptcha_html'] = $this->_create_recaptcha();
				} else {
					$data['captcha_html'] = $this->_create_captcha();
				}
			}

			//			$this->load->view('auth/login_form', $data);
			$pagedata = $this->get_share_pagedata();
			$pagedata['main_content'] = $this->load->view('auth/login_form', $data, true);
			$this->load->view('htmlpage/page_for_auth', $pagedata);
		}
	}

	/**
	 * Logout user
	 *
	 * @return void
	 */
	function logout()
	{
		$this->tank_auth->logout();
		//echo '121121';
		//退出登录时出错，只好将下句注释掉,并重定向到首页
		//		$this->_show_message($this->lang->line('auth_message_logged_out'));
		redirect('/');
		//echo 'after louout';
	}

	/**
	 * Register user on the site
	 *
	 * @return void
	 */
	function register()
	{
		if ($this->tank_auth->is_logged_in()) {									// logged in
			redirect('');
		} elseif ($this->tank_auth->is_logged_in(FALSE)) {						// logged in, not activated
			redirect('/auth/send_again/');
		} elseif (!$this->config->item('allow_registration', 'tank_auth')) {	// registration is off
			$this->_show_message($this->lang->line('auth_message_registration_disabled'));
		} else {
			$use_username = $this->config->item('use_username', 'tank_auth');
			if ($use_username) {
				$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|min_length[' . $this->config->item('username_min_length', 'tank_auth') . ']|max_length[' . $this->config->item('username_max_length', 'tank_auth') . ']|alpha_dash');
			}
			$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean|valid_email');
			$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|min_length[' . $this->config->item('password_min_length', 'tank_auth') . ']|max_length[' . $this->config->item('password_max_length', 'tank_auth') . ']|alpha_dash');
			$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|xss_clean|matches[password]');

			$captcha_registration	= $this->config->item('captcha_registration', 'tank_auth');
			$use_recaptcha			= $this->config->item('use_recaptcha', 'tank_auth');
			if ($captcha_registration) {
				if ($use_recaptcha) {
					$this->form_validation->set_rules('recaptcha_response_field', 'Confirmation Code', 'trim|xss_clean|required|callback__check_recaptcha');
				} else {
					$this->form_validation->set_rules('captcha', 'Confirmation Code', 'trim|xss_clean|required|callback__check_captcha');
				}
			}
			$data['errors'] = array();

			$email_activation = $this->config->item('email_activation', 'tank_auth');


			if ($this->form_validation->run()) {								// validation ok
				if (!is_null($data = $this->tank_auth->create_user(
					$use_username ? $this->form_validation->set_value('username') : '',
					$this->form_validation->set_value('email'),
					$this->form_validation->set_value('password'),
					$email_activation
				))) {									// success

					$data['site_name'] = $this->config->item('website_name', 'tank_auth');

					if ($email_activation) {									// send "activate" email
						$data['activation_period'] = $this->config->item('email_activation_expire', 'tank_auth') / 3600;

						$this->_send_email('activate', $data['email'], $data);

						unset($data['password']); // Clear password (just for any case)

						$this->_show_message($this->lang->line('auth_message_registration_completed_1'));
					} else {
						if ($this->config->item('email_account_details', 'tank_auth')) {	// send "welcome" email

							$this->_send_email('welcome', $data['email'], $data);
						}
						unset($data['password']); // Clear password (just for any case)

						$this->_show_message($this->lang->line('auth_message_registration_completed_2') . ' ' . anchor('/auth/login/', '登录'));
					}
				} else {
					$errors = $this->tank_auth->get_error_message();
					foreach ($errors as $k => $v)	$data['errors'][$k] = $this->lang->line($v);
				}
			}
			if ($captcha_registration) {
				if ($use_recaptcha) {
					$data['recaptcha_html'] = $this->_create_recaptcha();
				} else {
					$data['captcha_html'] = $this->_create_captcha();
				}
			}
			$data['use_username'] = $use_username;
			$data['captcha_registration'] = $captcha_registration;
			$data['use_recaptcha'] = $use_recaptcha;
						// $this->load->view('auth/register_form', $data);
						//  print_r($data);
			$pagedata = $this->get_share_pagedata();
			$pagedata['main_content'] = $this->load->view('auth/register_form', $data, true);
			$this->load->view('htmlpage/page_for_auth', $pagedata);
		}
	}

	/**
	 * Send activation email again, to the same or new email address
	 *
	 * @return void
	 */
	function send_again()
	{
		if (!$this->tank_auth->is_logged_in(FALSE)) {							// not logged in or activated
			redirect('/auth/login/');
		} else {
			$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean|valid_email');

			$data['errors'] = array();

			if ($this->form_validation->run()) {								// validation ok
				if (!is_null($data = $this->tank_auth->change_email(
					$this->form_validation->set_value('email')
				))) {			// success

					$data['site_name']	= $this->config->item('website_name', 'tank_auth');
					$data['activation_period'] = $this->config->item('email_activation_expire', 'tank_auth') / 3600;

					$this->_send_email('activate', $data['email'], $data);

					$this->_show_message(sprintf($this->lang->line('auth_message_activation_email_sent'), $data['email']));
				} else {
					$errors = $this->tank_auth->get_error_message();
					foreach ($errors as $k => $v)	$data['errors'][$k] = $this->lang->line($v);
				}
			}
			$this->load->view('auth/send_again_form', $data);
		}
	}

	/**
	 * Activate user account.
	 * User is verified by user_id and authentication code in the URL.
	 * Can be called by clicking on link in mail.
	 *
	 * @return void
	 */
	function activate()
	{
		$user_id		= $this->uri->segment(3);
		$new_email_key	= $this->uri->segment(4);

		// Activate user
		if ($this->tank_auth->activate_user($user_id, $new_email_key)) {		// success
			$this->tank_auth->logout();
			$this->_show_message($this->lang->line('auth_message_activation_completed') . ' ' . anchor('/auth/login/', 'Login'));
		} else {																// fail
			$this->_show_message($this->lang->line('auth_message_activation_failed'));
		}
	}

	/**
	 * Generate reset code (to change password) and send it to user
	 *
	 * @return void
	 */
	function forgot_password()
	{
		if ($this->tank_auth->is_logged_in()) {									// logged in
			redirect('');
		} elseif ($this->tank_auth->is_logged_in(FALSE)) {						// logged in, not activated
			redirect('/auth/send_again/');
		} else {
			$this->form_validation->set_rules('login', 'Email or login', 'trim|required|xss_clean');

			$data['errors'] = array();

			if ($this->form_validation->run()) {								// validation ok
				if (!is_null($data = $this->tank_auth->forgot_password(
					$this->form_validation->set_value('login')
				))) {

					$data['site_name'] = $this->config->item('website_name', 'tank_auth');

					// Send email with password activation link
					$this->_send_email('forgot_password', $data['email'], $data);

					$this->_show_message($this->lang->line('auth_message_new_password_sent'));
				} else {
					$errors = $this->tank_auth->get_error_message();
					foreach ($errors as $k => $v)	$data['errors'][$k] = $this->lang->line($v);
				}
			}
			//			$this->load->view('auth/forgot_password_form', $data);
			$pagedata = $this->get_share_pagedata();
			$pagedata['main_content'] = $this->load->view('auth/forgot_password_form', $data, true);
			$this->load->view('htmlpage/page_for_auth', $pagedata);
		}
	}

	/**
	 * Replace user password (forgotten) with a new one (set by user).
	 * User is verified by user_id and authentication code in the URL.
	 * Can be called by clicking on link in mail.
	 *
	 * @return void
	 */
	function reset_password()
	{
		$user_id		= $this->uri->segment(3);
		$new_pass_key	= $this->uri->segment(4);

		$this->form_validation->set_rules('new_password', 'New Password', 'trim|required|xss_clean|min_length[' . $this->config->item('password_min_length', 'tank_auth') . ']|max_length[' . $this->config->item('password_max_length', 'tank_auth') . ']|alpha_dash');
		$this->form_validation->set_rules('confirm_new_password', 'Confirm new Password', 'trim|required|xss_clean|matches[new_password]');

		$data['errors'] = array();

		if ($this->form_validation->run()) {								// validation ok
			if (!is_null($data = $this->tank_auth->reset_password(
				$user_id,
				$new_pass_key,
				$this->form_validation->set_value('new_password')
			))) {	// success

				$data['site_name'] = $this->config->item('website_name', 'tank_auth');

				// Send email with new password
				$this->_send_email('reset_password', $data['email'], $data);

				$this->_show_message($this->lang->line('auth_message_new_password_activated') . ' ' . anchor('/auth/login/', 'Login'));
			} else {														// fail
				$this->_show_message($this->lang->line('auth_message_new_password_failed'));
			}
		} else {
			// Try to activate user by password key (if not activated yet)
			if ($this->config->item('email_activation', 'tank_auth')) {
				$this->tank_auth->activate_user($user_id, $new_pass_key, FALSE);
			}

			if (!$this->tank_auth->can_reset_password($user_id, $new_pass_key)) {
				$this->_show_message($this->lang->line('auth_message_new_password_failed'));
			}
		}
		//		$this->load->view('auth/reset_password_form', $data);
		$pagedata = $this->get_share_pagedata();
		$pagedata['main_content'] = $this->load->view('auth/reset_password_form', $data, true);
		$this->load->view('htmlpage/page_for_auth', $pagedata);
	}

	/**
	 * Change user password
	 *
	 * @return void
	 */
	function change_password()
	{
		if (!$this->tank_auth->is_logged_in()) {								// not logged in or not activated
			redirect('/auth/login/');
		} else {
			$this->form_validation->set_rules('old_password', 'Old Password', 'trim|required|xss_clean');
			$this->form_validation->set_rules('new_password', 'New Password', 'trim|required|xss_clean|min_length[' . $this->config->item('password_min_length', 'tank_auth') . ']|max_length[' . $this->config->item('password_max_length', 'tank_auth') . ']|alpha_dash');
			$this->form_validation->set_rules('confirm_new_password', 'Confirm new Password', 'trim|required|xss_clean|matches[new_password]');

			$data['errors'] = array();

			if ($this->form_validation->run()) {								// validation ok
				if ($this->tank_auth->change_password(
					$this->form_validation->set_value('old_password'),
					$this->form_validation->set_value('new_password')
				)) {	// success
					$this->_show_message($this->lang->line('auth_message_password_changed'));
				} else {														// fail
					$errors = $this->tank_auth->get_error_message();
					foreach ($errors as $k => $v)	$data['errors'][$k] = $this->lang->line($v);
				}
			}
			//$this->load->view('auth/change_password_form', $data);
			$pagedata = $this->get_share_pagedata();
			$pagedata['main_content'] = $this->load->view('auth/change_password_form', $data, true);
			$this->load->view('htmlpage/page_for_auth', $pagedata);
		}
	}

	/**
	 * Change user email
	 *
	 * @return void
	 */
	function change_email()
	{
		if (!$this->tank_auth->is_logged_in()) {								// not logged in or not activated
			redirect('/auth/login/');
		} else {
			$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
			$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean|valid_email');

			$data['errors'] = array();

			if ($this->form_validation->run()) {								// validation ok
				if (!is_null($data = $this->tank_auth->set_new_email(
					$this->form_validation->set_value('email'),
					$this->form_validation->set_value('password')
				))) {			// success

					$data['site_name'] = $this->config->item('website_name', 'tank_auth');

					// Send email with new email address and its activation link
					$this->_send_email('change_email', $data['new_email'], $data);

					$this->_show_message(sprintf($this->lang->line('auth_message_new_email_sent'), $data['new_email']));
				} else {
					$errors = $this->tank_auth->get_error_message();
					foreach ($errors as $k => $v)	$data['errors'][$k] = $this->lang->line($v);
				}
			}
			$this->load->view('auth/change_email_form', $data);
		}
	}

	/**
	 * Replace user email with a new one.
	 * User is verified by user_id and authentication code in the URL.
	 * Can be called by clicking on link in mail.
	 *
	 * @return void
	 */
	function reset_email()
	{
		$user_id		= $this->uri->segment(3);
		$new_email_key	= $this->uri->segment(4);

		// Reset email
		if ($this->tank_auth->activate_new_email($user_id, $new_email_key)) {	// success
			$this->tank_auth->logout();
			$this->_show_message($this->lang->line('auth_message_new_email_activated') . ' ' . anchor('/auth/login/', 'Login'));
		} else {																// fail
			$this->_show_message($this->lang->line('auth_message_new_email_failed'));
		}
	}

	/**
	 * Delete user from the site (only when user is logged in)
	 *
	 * @return void
	 */
	function unregister()
	{
		if (!$this->tank_auth->is_logged_in()) {								// not logged in or not activated
			redirect('/auth/login/');
		} else {
			$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');

			$data['errors'] = array();

			if ($this->form_validation->run()) {								// validation ok
				if ($this->tank_auth->delete_user(
					$this->form_validation->set_value('password')
				)) {		// success
					$this->_show_message($this->lang->line('auth_message_unregistered'));
				} else {														// fail
					$errors = $this->tank_auth->get_error_message();
					foreach ($errors as $k => $v)	$data['errors'][$k] = $this->lang->line($v);
				}
			}
			$this->load->view('auth/unregister_form', $data);
		}
	}

	/**
	 * Show info message
	 *
	 * @param	string
	 * @return	void
	 */
	function _show_message($message)
	{

		$this->session->set_flashdata('message', $message);
		redirect('/auth/');
		//redirect('/');//20150405 add by chenyuquan,logout时总是出错，所以将前两句注释了，换这行
	}


	/**
	 * Send email message of given type (activate, forgot_password, etc.)
	 *
	 * @param	string
	 * @param	string
	 * @param	array
	 * @return	void
	 */
	function _send_email($type, $email, &$data)
	{
		$this->load->library('email');
		$this->email->from($this->config->item('webmaster_email', 'tank_auth'), $this->config->item('website_name', 'tank_auth'));
		$this->email->reply_to($this->config->item('webmaster_email', 'tank_auth'), $this->config->item('website_name', 'tank_auth'));
		$this->email->to($email);
		$this->email->subject(sprintf($this->lang->line('auth_subject_' . $type), $this->config->item('website_name', 'tank_auth')));
		$this->email->message($this->load->view('email/' . $type . '-html', $data, TRUE));
		$this->email->set_alt_message($this->load->view('email/' . $type . '-txt', $data, TRUE));
		$this->email->send();
	}

	/**
	 * Create CAPTCHA image to verify user as a human
	 *
	 * @return	string
	 */
	function _create_captcha()
	{
		
		$this->load->helper('captcha');
		
		$cap = create_captcha(array(
			'img_path'		=> './' . $this->config->item('captcha_path', 'tank_auth'),
			'img_url'		=> base_url() . $this->config->item('captcha_path', 'tank_auth'),
			'font_path'		=> './' . $this->config->item('captcha_fonts_path', 'tank_auth'),
			'font_size'		=> $this->config->item('captcha_font_size', 'tank_auth'),
			'img_width'		=> $this->config->item('captcha_width', 'tank_auth'),
			'img_height'	=> $this->config->item('captcha_height', 'tank_auth'),
			'show_grid'		=> $this->config->item('captcha_grid', 'tank_auth'),
			'expiration'	=> $this->config->item('captcha_expire', 'tank_auth'),
		));
		
		// print_r($cap);

		// Save captcha params in session
		$this->session->set_flashdata(array(
			'captcha_word' => $cap['word'],
			'captcha_time' => $cap['time'],
		));

		return $cap['image'];
	}

	/**
	 * Callback function. Check if CAPTCHA test is passed.
	 *
	 * @param	string
	 * @return	bool
	 */
	function _check_captcha($code)
	{
		$time = $this->session->flashdata('captcha_time');
		$word = $this->session->flashdata('captcha_word');

		list($usec, $sec) = explode(" ", microtime());
		$now = ((float)$usec + (float)$sec);

		if ($now - $time > $this->config->item('captcha_expire', 'tank_auth')) {
			$this->form_validation->set_message('_check_captcha', $this->lang->line('auth_captcha_expired'));
			return FALSE;
		} elseif (($this->config->item('captcha_case_sensitive', 'tank_auth') and
				$code != $word) or
			strtolower($code) != strtolower($word)
		) {
			$this->form_validation->set_message('_check_captcha', $this->lang->line('auth_incorrect_captcha'));
			return FALSE;
		}
		return TRUE;
	}

	/**
	 * Create reCAPTCHA JS and non-JS HTML to verify user as a human
	 *
	 * @return	string
	 */
	function _create_recaptcha()
	{
		$this->load->helper('recaptcha');

		// Add custom theme so we can get only image
		$options = "<script>var RecaptchaOptions = {theme: 'custom', custom_theme_widget: 'recaptcha_widget'};</script>\n";

		// Get reCAPTCHA JS and non-JS HTML
		$html = recaptcha_get_html($this->config->item('recaptcha_public_key', 'tank_auth'));

		return $options . $html;
	}

	/**
	 * Callback function. Check if reCAPTCHA test is passed.
	 *
	 * @return	bool
	 */
	function _check_recaptcha()
	{
		$this->load->helper('recaptcha');

		$resp = recaptcha_check_answer(
			$this->config->item('recaptcha_private_key', 'tank_auth'),
			$_SERVER['REMOTE_ADDR'],
			$_POST['recaptcha_challenge_field'],
			$_POST['recaptcha_response_field']
		);

		if (!$resp->is_valid) {
			$this->form_validation->set_message('_check_recaptcha', $this->lang->line('auth_incorrect_captcha'));
			return FALSE;
		}
		return TRUE;
	}
}

/* End of file auth.php */
/* Location: ./application/controllers/auth.php */